package com.bigfans.framework.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @author lichong
 * @version V1.0
 * @Title:
 * @Description: redis操作封装, 线程安全
 * @date 2016年1月26日 上午9:01:23
 */
public class JedisTemplate {

    private JedisConnectionFactory connectionFactory;

    private Logger logger = LoggerFactory.getLogger(JedisTemplate.class);

    public JedisTemplate() {
    }

    public JedisTemplate(JedisConnectionFactory connectionFactory) {
        this.connectionFactory = connectionFactory;
    }

    public <T> T execute(JedisExecuteCallback<T> callback) {
        JedisConnection conn = null;
        T result = null;
        try {
            conn = getConnectionFactory().getConnection();
            result = callback.runInConnection(conn);
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.release();
            }
        }
        return result;
    }

    public void execute(JedisExecuteWithoutReturnCallback callback) {
        JedisConnection conn = null;
        try {
            conn = getConnectionFactory().getConnection();
            callback.runInConnection(conn);
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.release();
            }
        }
    }

    public List<Object> executeInPipeline(JedisExecuteWithoutReturnCallback callback) {
        JedisConnection conn = null;
        List<Object> result = null;
        try {
            conn = getConnectionFactory().getConnection();
            conn.openPipeline();
            callback.runInConnection(conn);
            result = conn.closePipeline(true);
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.release();
            }
        }
        return result;
    }

    public void publish(final String channel, final String message) {
        this.executeInPipeline(new JedisExecuteWithoutReturnCallback() {
            public void runInConnection(JedisConnection conn) {
                conn.publish(channel, message);
            }
        });
    }

    public void subscribe(final JedisSubscriber subscriber, final String... channels) {
        this.execute(new JedisExecuteWithoutReturnCallback() {
            public void runInConnection(JedisConnection conn) {
                conn.subscribe(subscriber, channels);
            }
        });
    }

    public JedisConnectionFactory getConnectionFactory() {
        return connectionFactory;
    }

    public void setConnectionFactory(JedisConnectionFactory connectionFactory) {
        this.connectionFactory = connectionFactory;
    }
}
